package com.home.utils;


import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.io.InputStream;
import java.util.Date;
import java.util.Properties;

/**
 * Created by origin on 15-5-10.
 */
public class SendEmail {
    public static void sendEmail(String to,String subject,String content)throws Exception{
        Properties properties = new Properties();
        InputStream resourceAsStream = null;
        try {
            resourceAsStream = SendEmail.class.getResourceAsStream("/email.properties");
            properties.load(resourceAsStream);
        } finally{
            if (resourceAsStream!=null) {
                resourceAsStream.close();
            }
        }
        properties.put("mail.smtp.host", properties.get("mail.smtp.host"));
        properties.put("mail.smtp.port", properties.get("mail.smtp.port"));
        properties.put("mail.smtp.auth", "true");
        Authenticator authenticator = new EmailAuthenticator(properties.get("username").toString(), properties.get("password").toString());
        javax.mail.Session sendMailSession = javax.mail.Session.getDefaultInstance(properties, authenticator);
        MimeMessage mailMessage = new MimeMessage(sendMailSession);
        mailMessage.setFrom(new InternetAddress(properties.get("username").toString()));
        // Message.RecipientType.TO属性表示接收者的类型为TO
        mailMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
        mailMessage.setSubject(subject, "UTF-8");
        mailMessage.setSentDate(new Date());
        // MiniMultipart类是一个容器类，包含MimeBodyPart类型的对象
        Multipart mainPart = new MimeMultipart();
        // 创建一个包含HTML内容的MimeBodyPart
        BodyPart html = new MimeBodyPart();
        html.setContent(content.trim(), "text/html; charset=utf-8");
        mainPart.addBodyPart(html);
        mailMessage.setContent(mainPart);
        Transport.send(mailMessage);
    }
    public static void main(String arg[]){
        try {
            SendEmail.sendEmail("3245856068@qq.com","合作申请","<center><h2>呵呵 我的 test 13443432323</h2></center>");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
